﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using mojoPortal.Web;
using mojoPortal.Web.Editor;
using mojoPortal.Web.Framework;
using mojoPortal.Web.UI;
using mojoPortal.Business;
using mojoPortal.Business.WebHelpers;
using eStore.Business;
using eStore.Helpers;
using Resources;
using System.Configuration;
using ud_Utilities;
using System.Drawing;

namespace eStore.UI
{
    public partial class AdminProductEditPage : mojoBasePage
    {
        private int pageId = -1;
        private int moduleId = -1;
        private Store store;
        private Guid productGuid = Guid.Empty;
        private SiteUser siteUser;
        private Double timeOffset;
        private TimeZoneInfo timeZone;
        private readonly CultureInfo currencyCulture = CultureInfo.CurrentCulture;
        private int intSortRank1;
        private int intSortRank2;
        readonly ContentMetaRespository metaRepository = new ContentMetaRespository();
        protected eStoreConfiguration config = new eStoreConfiguration();
        private Product product;
        private readonly eStoreDB repository = new eStoreDB();

        protected void Page_Load(object sender, EventArgs e)
        {
            Page.EnableViewState = true;
            LoadParams();

            if (!UserCanEditModule(moduleId))
            {
                SiteUtils.RedirectToAccessDeniedPage();
                return;
            }
            LoadSettings();

            CheckCategory();

            SetupCss();
            PopulateLabels();
            PopulateControls();

        }

        private void CheckCategory()
        {
            int totalCategories;
            repository.GeteStoreCategoriesByModuleID(moduleId, out totalCategories);
            if (totalCategories.Equals(0))
            {
                pnlNoCategory.Visible = true;
                pnlMain.Visible = false;
            }
            else
            {
                pnlMain.Visible = true;
                pnlNoCategory.Visible = false;
            }
        }

        private void PopulateControls()
        {
            if (store == null) { return; }

            if (!Page.IsPostBack)
            {
                PopulateTaxClassList();
                PopulateProductControls();
                BindMeta();
                BindMetaLinks();
                PopulateRootCategories();
            }

            if (productGuid == Guid.Empty)
            {
                btnDelete.Visible = false;
            }
            if (product != null)
            {
                if (!string.IsNullOrEmpty(product.ImageUrl))
                {
                    divImage.Visible = true;
                    imgView.ImageUrl = "~/" + ConfigurationManager.AppSettings["eStoreImagesFolder"] + product.ImageUrl;
                }
                else { divImage.Visible = false; }
            }

            chkIsVisible.Checked = true;
        }
        private void PopulateRootCategories()
        {
            lbCategory.DataSource = repository.GeteStoreRootCategoriesByModuleID(moduleId);
            lbCategory.DataTextField = "Name";
            lbCategory.DataValueField = "CategoryID";
            lbCategory.DataBind();
            PopulateChildNode(lbCategory);
            if (lbCategory.Items.Count > 0)
            {
                if (productGuid.Equals(Guid.Empty))
                {
                    lbCategory.SelectedIndex = 0;
                }
                else
                {
                    lbCategory.Items.FindByValue(product.CategoryID.ToString()).Selected = true;
                }
            }
        }

        private void PopulateChildNode(ListBox root)
        {
            for (int i = 0; i < root.Items.Count; i++)
            {
                List<ud_eStoreCategory> children = repository.GeteStoreChildCategoryByCatID(int.Parse(root.Items[i].Value));
                if (children.Count > 0)
                {
                    string prefix = string.Empty;
                    while (root.Items[i].Text.StartsWith("-"))
                    {
                        prefix += root.Items[i].Text.Substring(0, 3);
                        root.Items[i].Text = root.Items[i].Text.Remove(0, 3);
                    }
                    root.Items[i].Text = prefix + root.Items[i].Text;
                    foreach (ud_eStoreCategory child in children)
                    {
                        ListItem list = new ListItem
                        {
                            Text = prefix + @"---" + child.Name,
                            Value = child.CategoryID.ToString()
                        };
                        root.Items.Insert(root.Items.IndexOf(root.Items[i]) + 1, list);
                    }
                }
            }
        }

        private void PopulateProductControls()
        {
            if (store == null) { return; }

            if (productGuid != Guid.Empty)
            {
                Title = SiteUtils.FormatPageTitle(siteSettings, eStoreResources.ProductEditHeading + " - " + product.Name);
                txtName.Text = product.Name;
                txtPrice.Text = product.Price.ToString("0");
                edDescription.Text = product.Description;
                txtSortRank1.Text = product.SortRank1.ToInvariantString();
                txtSortRank2.Text = product.SortRank2.ToInvariantString();
                txtMetaDescription.Text = product.MetaDescription;
                txtMetaKeywords.Text = product.MetaKeywords;

                ListItem listItem = ddTaxClassGuid.Items.FindByValue(product.TaxClassGuid.ToString());
                if (listItem != null)
                {
                    ddTaxClassGuid.ClearSelection();
                    listItem.Selected = true;
                }

                chkIsVisible.Checked = product.IsVisible;
                chkIsSpecial.Checked = product.IsSpecial;
                chkIsDonation.Checked = product.IsDonation;
            }

        }


        private void PopulateTaxClassList()
        {
            using (IDataReader reader = TaxClass.GetBySite(siteSettings.SiteGuid))
            {
                ddTaxClassGuid.DataSource = reader;
                ddTaxClassGuid.DataBind();
            }

        }

        private bool Save()
        {
            if (store == null) { return false; }

            if (productGuid.Equals(Guid.Empty))
            {
                product = new Product
                              {
                                  Created = DateTime.UtcNow,
                                  CreatedBy = siteUser.UserGuid,
                                  CreatedFromIP = SiteUtils.GetIP4Address()
                              };
            }

            if (config.IndexProductsInSearch)
            {
                product.ContentChanged += product_ContentChanged;
            }

            product.Name = txtName.Text;
            product.Description = edDescription.Text;
            product.StoreGuid = store.Guid;
            product.IsVisible = chkIsVisible.Checked;
            product.IsSpecial = chkIsSpecial.Checked;
            product.IsDonation = chkIsDonation.Checked;
            product.MetaDescription = txtMetaDescription.Text;
            product.MetaKeywords = txtMetaKeywords.Text;

            // If the sort rank inputs are left null on the product
            //		and Product creation screens, the in.Parse gets all
            //		bent out of shape so I converted to TryParse	
            if (int.TryParse(txtSortRank1.Text, NumberStyles.Number, CultureInfo.InvariantCulture, out intSortRank1))
            {
                product.SortRank1 = intSortRank1;
            }
            if (int.TryParse(txtSortRank2.Text, NumberStyles.Number, CultureInfo.InvariantCulture, out intSortRank2))
            {
                product.SortRank2 = intSortRank2;
            }

            product.Price = decimal.Parse(txtPrice.Text);

            if (!String.IsNullOrEmpty(ddTaxClassGuid.SelectedValue))
            {
                Guid taxClassGuid = new Guid(ddTaxClassGuid.SelectedValue);
                product.TaxClassGuid = taxClassGuid;
            }

            product.LastModified = DateTime.UtcNow;
            product.LastModifiedBy = siteUser.UserGuid;
            product.LastModifiedFromIP = SiteUtils.GetIP4Address();
            product.CategoryID = int.Parse(lbCategory.SelectedValue);
            bool needToCreateFriendlyUrl = false;

            if ((product.Url.Length == 0) && (txtName.Text.Length > 0))
            {
                product.Url = "/"
                    + SiteUtils.SuggestFriendlyUrl(
                    txtName.Text + eStoreResources.ProductUrlSuffix,
                    siteSettings);

                needToCreateFriendlyUrl = true;

            }
            string fileName;
            if (!SaveImageUrl(out fileName))
            {
                return false;
            }
            if (!fileName.Equals(string.Empty))
            {
                product.ImageUrl = fileName;
            }

            if (product.Save())
            {
                productGuid = product.Guid;

                if (needToCreateFriendlyUrl)
                {

                    FriendlyUrl newUrl = new FriendlyUrl
                                             {
                                                 SiteId = siteSettings.SiteId,
                                                 SiteGuid = siteSettings.SiteGuid,
                                                 PageGuid = product.Guid,
                                                 Url = product.Url.Replace("/", string.Empty),
                                                 RealUrl = "~/eStore/ProductDetail.aspx?pageid="
                                                           + pageId.ToInvariantString()
                                                           + "&mid=" + moduleId.ToInvariantString()
                                                           + "&Product=" + product.Guid
                                             };

                    newUrl.Save();

                }


            }
            SiteUtils.QueueIndexing();
            WebUtils.SetupRedirect(this, GetReturnUrl());
            return true;
        }

        void product_ContentChanged(object sender, ContentChangedEventArgs e)
        {
            IndexBuilderProvider indexBuilder = IndexBuilderManager.Providers["eStoreProductIndexBuilderProvider"];
            if (indexBuilder != null)
            {
                indexBuilder.ContentChangedHandler(sender, e);
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (productGuid != Guid.Empty)
            {
                if (config.IndexProductsInSearch)
                {
                    Product product1 = new Product(productGuid);
                    ContentChangedEventArgs args = new ContentChangedEventArgs {IsDeleted = true};
                    product_ContentChanged(product1, args);
                }

                FriendlyUrl.DeleteByPageGuid(productGuid);

                Product.Delete(productGuid);

                SiteUtils.QueueIndexing();
                WebUtils.SetupRedirect(this, GetReturnUrl());
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            Page.Validate("Product");
            if ((Page.IsValid) && (IsValidForSave()))
            {
                Save();
            }

        }

        private bool IsValidForSave()
        {
            decimal priceTest;
            if (!decimal.TryParse(txtPrice.Text, NumberStyles.Currency, currencyCulture, out priceTest))
            {
                lblError.Text = eStoreResources.ProductPriceInvalidMessage;
                return false;
            }

            return true;
        }

        #region Meta Data

        private void BindMeta()
        {
            if (productGuid == Guid.Empty) { return; }
            if (store == null) { return; }
            Product product1 = new Product(productGuid);
            if (product1.StoreGuid != store.Guid) { return; }

            List<ContentMeta> meta = metaRepository.FetchByContent(product1.Guid);
            grdContentMeta.DataSource = meta;
            grdContentMeta.DataBind();

            btnAddMeta.Visible = true;
        }

        void grdContentMeta_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (productGuid == Guid.Empty) { return; }
            if (store == null) { return; }
            Product product1 = new Product(productGuid);
            if (product1.StoreGuid != store.Guid) { return; }

            string sGuid = e.CommandArgument.ToString();
            if (sGuid.Length != 36) { return; }

            Guid guid = new Guid(sGuid);
            ContentMeta meta = metaRepository.Fetch(guid);
            if (meta == null) { return; }

            switch (e.CommandName)
            {
                case "MoveUp":
                    meta.SortRank -= 3;
                    break;

                case "MoveDown":
                    meta.SortRank += 3;
                    break;

            }

            metaRepository.Save(meta);
            List<ContentMeta> metaList = metaRepository.FetchByContent(product1.Guid);
            metaRepository.ResortMeta(metaList);

            product1.CompiledMeta = metaRepository.GetMetaString(product1.Guid);
            product1.Save();

            BindMeta();
            upMeta.Update();


        }



        void grdContentMeta_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            if (productGuid == Guid.Empty) { return; }
            if (store == null) { return; }
            Product product1 = new Product(productGuid);
            if (product1.StoreGuid != store.Guid) { return; }

            GridView grid = (GridView)sender;
// ReSharper disable PossibleNullReferenceException
            Guid guid = new Guid(grid.DataKeys[e.RowIndex].Value.ToString());
// ReSharper restore PossibleNullReferenceException
            metaRepository.Delete(guid);

            product1.CompiledMeta = metaRepository.GetMetaString(product1.Guid);
            product1.Save();
            grdContentMeta.Columns[2].Visible = true;
            BindMeta();
            upMeta.Update();
        }

        void grdContentMeta_RowEditing(object sender, GridViewEditEventArgs e)
        {
            GridView grid = (GridView)sender;
            grid.EditIndex = e.NewEditIndex;

            BindMeta();

            //Guid guid = new Guid(grid.DataKeys[grid.EditIndex].Value.ToString());

            Button btnDeleteMeta = (Button)grid.Rows[e.NewEditIndex].Cells[1].FindControl("btnDeleteMeta");
            if (btnDeleteMeta != null)
            {
                btnDelete.Attributes.Add("OnClick", "return confirm('"
                    + eStoreResources.ContentMetaDeleteWarning + "');");

                //if (guid == Guid.Empty) { btnDeleteMeta.Visible = false; }
            }

            upMeta.Update();
        }

        void grdContentMeta_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            GridView grid = (GridView)sender;
            if (grid.EditIndex > -1)
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    DropDownList ddDirection = (DropDownList)e.Row.Cells[1].FindControl("ddDirection");
                    if (ddDirection != null)
                    {
                        if (e.Row.DataItem is ContentMeta)
                        {
                            ListItem item = ddDirection.Items.FindByValue(((ContentMeta)e.Row.DataItem).Dir);
                            if (item != null)
                            {
                                ddDirection.ClearSelection();
                                item.Selected = true;
                            }
                        }

                    }

                    if (!(e.Row.DataItem is ContentMeta))
                    {
                        //the add button was clicked so hide the delete button
                        Button btnDeleteMeta = (Button)e.Row.Cells[1].FindControl("btnDeleteMeta");
                        if (btnDeleteMeta != null) { btnDeleteMeta.Visible = false; }

                    }

                }

            }

        }

        void grdContentMeta_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            if (productGuid == Guid.Empty) { return; }
            if (store == null) { return; }
            Product product1 = new Product(productGuid);
            if (product1.StoreGuid != store.Guid) { return; }

            GridView grid = (GridView)sender;

// ReSharper disable PossibleNullReferenceException
            Guid guid = new Guid(grid.DataKeys[e.RowIndex].Value.ToString());
// ReSharper restore PossibleNullReferenceException
            TextBox name = (TextBox)grid.Rows[e.RowIndex].Cells[1].FindControl("txtName");
            TextBox txtScheme = (TextBox)grid.Rows[e.RowIndex].Cells[1].FindControl("txtScheme");
            TextBox txtLangCode = (TextBox)grid.Rows[e.RowIndex].Cells[1].FindControl("txtLangCode");
            DropDownList ddDirection = (DropDownList)grid.Rows[e.RowIndex].Cells[1].FindControl("ddDirection");
            TextBox txtMetaContent = (TextBox)grid.Rows[e.RowIndex].Cells[1].FindControl("txtMetaContent");

            ContentMeta meta;
            if (guid != Guid.Empty)
            {
                meta = metaRepository.Fetch(guid);
            }
            else
            {
                meta = new ContentMeta();
                if (siteUser != null) { meta.CreatedBy = siteUser.UserGuid; }
                meta.SortRank = metaRepository.GetNextSortRank(product1.Guid);
                meta.ModuleGuid = store.ModuleGuid;
            }

            if (meta != null)
            {
                meta.SiteGuid = siteSettings.SiteGuid;
                meta.ContentGuid = product1.Guid;
                meta.Dir = ddDirection.SelectedValue;
                meta.LangCode = txtLangCode.Text;
                meta.MetaContent = txtMetaContent.Text;
                meta.Name = name.Text;
                meta.Scheme = txtScheme.Text;
                if (siteUser != null) { meta.LastModBy = siteUser.UserGuid; }
                metaRepository.Save(meta);

                product1.CompiledMeta = metaRepository.GetMetaString(product1.Guid);
                product1.Save();

            }

            grid.EditIndex = -1;
            grdContentMeta.Columns[2].Visible = true;
            BindMeta();
            upMeta.Update();

        }

        void grdContentMeta_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            grdContentMeta.EditIndex = -1;
            grdContentMeta.Columns[2].Visible = true;
            BindMeta();
            upMeta.Update();
        }

        void btnAddMeta_Click(object sender, EventArgs e)
        {
            DataTable dataTable = new DataTable();
            dataTable.Columns.Add("Guid", typeof(Guid));
            dataTable.Columns.Add("SiteGuid", typeof(Guid));
            dataTable.Columns.Add("ModuleGuid", typeof(Guid));
            dataTable.Columns.Add("ContentGuid", typeof(Guid));
            dataTable.Columns.Add("Name", typeof(string));
            dataTable.Columns.Add("Scheme", typeof(string));
            dataTable.Columns.Add("LangCode", typeof(string));
            dataTable.Columns.Add("Dir", typeof(string));
            dataTable.Columns.Add("MetaContent", typeof(string));
            dataTable.Columns.Add("SortRank", typeof(int));

            DataRow row = dataTable.NewRow();
            row["Guid"] = Guid.Empty;
            row["SiteGuid"] = siteSettings.SiteGuid;
            row["ModuleGuid"] = Guid.Empty;
            row["ContentGuid"] = Guid.Empty;
            row["Name"] = string.Empty;
            row["Scheme"] = string.Empty;
            row["LangCode"] = string.Empty;
            row["Dir"] = string.Empty;
            row["MetaContent"] = string.Empty;
            row["SortRank"] = 3;

            dataTable.Rows.Add(row);

            grdContentMeta.EditIndex = 0;
            grdContentMeta.DataSource = dataTable.DefaultView;
            grdContentMeta.DataBind();
            grdContentMeta.Columns[2].Visible = false;
            btnAddMeta.Visible = false;

            upMeta.Update();

        }

        private void BindMetaLinks()
        {
            if (productGuid == Guid.Empty) { return; }
            if (store == null) { return; }
            Product product1 = new Product(productGuid);
            if (product1.StoreGuid != store.Guid) { return; }

            List<ContentMetaLink> meta = metaRepository.FetchLinksByContent(product1.Guid);

            grdMetaLinks.DataSource = meta;
            grdMetaLinks.DataBind();

            btnAddMetaLink.Visible = true;
        }

        void btnAddMetaLink_Click(object sender, EventArgs e)
        {
            DataTable dataTable = new DataTable();
            dataTable.Columns.Add("Guid", typeof(Guid));
            dataTable.Columns.Add("SiteGuid", typeof(Guid));
            dataTable.Columns.Add("ModuleGuid", typeof(Guid));
            dataTable.Columns.Add("ContentGuid", typeof(Guid));
            dataTable.Columns.Add("Rel", typeof(string));
            dataTable.Columns.Add("Href", typeof(string));
            dataTable.Columns.Add("HrefLang", typeof(string));
            dataTable.Columns.Add("SortRank", typeof(int));

            DataRow row = dataTable.NewRow();
            row["Guid"] = Guid.Empty;
            row["SiteGuid"] = siteSettings.SiteGuid;
            row["ModuleGuid"] = Guid.Empty;
            row["ContentGuid"] = Guid.Empty;
            row["Rel"] = string.Empty;
            row["Href"] = string.Empty;
            row["HrefLang"] = string.Empty;
            row["SortRank"] = 3;

            dataTable.Rows.Add(row);

            grdMetaLinks.Columns[2].Visible = false;
            grdMetaLinks.EditIndex = 0;
            grdMetaLinks.DataSource = dataTable.DefaultView;
            grdMetaLinks.DataBind();
            btnAddMetaLink.Visible = false;

            updMetaLinks.Update();
        }

        void grdMetaLinks_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            GridView grid = (GridView)sender;
            if (grid.EditIndex > -1)
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    if (!(e.Row.DataItem is ContentMetaLink))
                    {
                        //the add button was clicked so hide the delete button
                        Button btnDeleteMetaLink = (Button)e.Row.Cells[1].FindControl("btnDeleteMetaLink");
                        if (btnDeleteMetaLink != null) { btnDeleteMetaLink.Visible = false; }

                    }

                }

            }
        }

        void grdMetaLinks_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            if (productGuid == Guid.Empty) { return; }
            if (store == null) { return; }
            Product product1 = new Product(productGuid);
            if (product1.StoreGuid != store.Guid) { return; }

            GridView grid = (GridView)sender;
// ReSharper disable PossibleNullReferenceException
            Guid guid = new Guid(grid.DataKeys[e.RowIndex].Value.ToString());
// ReSharper restore PossibleNullReferenceException
            metaRepository.DeleteLink(guid);

            product1.CompiledMeta = metaRepository.GetMetaString(product1.Guid);
            product1.Save();

            grid.Columns[2].Visible = true;
            BindMetaLinks();

            updMetaLinks.Update();
        }

        void grdMetaLinks_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            grdMetaLinks.EditIndex = -1;
            grdMetaLinks.Columns[2].Visible = true;
            BindMetaLinks();
            updMetaLinks.Update();
        }

        void grdMetaLinks_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            if (productGuid == Guid.Empty) { return; }
            if (store == null) { return; }
            Product product1 = new Product(productGuid);
            if (product1.StoreGuid != store.Guid) { return; }

            GridView grid = (GridView)sender;

// ReSharper disable PossibleNullReferenceException
            Guid guid = new Guid(grid.DataKeys[e.RowIndex].Value.ToString());
// ReSharper restore PossibleNullReferenceException
            TextBox txtRel = (TextBox)grid.Rows[e.RowIndex].Cells[1].FindControl("txtRel");
            TextBox txtHref = (TextBox)grid.Rows[e.RowIndex].Cells[1].FindControl("txtHref");
            TextBox txtHrefLang = (TextBox)grid.Rows[e.RowIndex].Cells[1].FindControl("txtHrefLang");

            ContentMetaLink meta;
            if (guid != Guid.Empty)
            {
                meta = metaRepository.FetchLink(guid);
            }
            else
            {
                meta = new ContentMetaLink();
                if (siteUser != null) { meta.CreatedBy = siteUser.UserGuid; }
                meta.SortRank = metaRepository.GetNextLinkSortRank(product1.Guid);
                meta.ModuleGuid = store.ModuleGuid;
            }

            if (meta != null)
            {
                meta.SiteGuid = siteSettings.SiteGuid;
                meta.ContentGuid = product1.Guid;
                meta.Rel = txtRel.Text;
                meta.Href = txtHref.Text;
                meta.HrefLang = txtHrefLang.Text;

                if (siteUser != null) { meta.LastModBy = siteUser.UserGuid; }
                metaRepository.Save(meta);

                product1.CompiledMeta = metaRepository.GetMetaString(product1.Guid);
                product1.Save();

            }

            grid.EditIndex = -1;
            grdMetaLinks.Columns[2].Visible = true;
            BindMetaLinks();
            updMetaLinks.Update();
        }

        void grdMetaLinks_RowEditing(object sender, GridViewEditEventArgs e)
        {
            GridView grid = (GridView)sender;
            grid.EditIndex = e.NewEditIndex;

            BindMetaLinks();

// ReSharper disable PossibleNullReferenceException
            Guid guid = new Guid(grid.DataKeys[grid.EditIndex].Value.ToString());
// ReSharper restore PossibleNullReferenceException

            Button delete = (Button)grid.Rows[e.NewEditIndex].Cells[1].FindControl("btnDeleteMetaLink");
            if (delete != null)
            {
                delete.Attributes.Add("OnClick", "return confirm('"
                    + eStoreResources.ContentMetaLinkDeleteWarning + "');");

                if (guid == Guid.Empty) { delete.Visible = false; }
            }

            updMetaLinks.Update();
        }

        void grdMetaLinks_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (productGuid == Guid.Empty) { return; }
            if (store == null) { return; }
            Product product1 = new Product(productGuid);
            if (product1.StoreGuid != store.Guid) { return; }

            string sGuid = e.CommandArgument.ToString();
            if (sGuid.Length != 36) { return; }

            Guid guid = new Guid(sGuid);
            ContentMetaLink meta = metaRepository.FetchLink(guid);
            if (meta == null) { return; }

            switch (e.CommandName)
            {
                case "MoveUp":
                    meta.SortRank -= 3;
                    break;

                case "MoveDown":
                    meta.SortRank += 3;
                    break;

            }

            metaRepository.Save(meta);
            List<ContentMetaLink> metaList = metaRepository.FetchLinksByContent(product1.Guid);
            metaRepository.ResortMeta(metaList);

            product1.CompiledMeta = metaRepository.GetMetaString(product1.Guid);
            product1.Save();

            BindMetaLinks();
            updMetaLinks.Update();
        }


        #endregion



        private void PopulateLabels()
        {
            lnkStoreMenu.Text = eStoreResources.StoreManagerHeading;
            lnkStoreMenu.NavigateUrl = SiteRoot + "/eStore/AdminDashboard.aspx?pageid="
                                       + pageId.ToString(CultureInfo.InvariantCulture)
                                       + "&mid=" + moduleId.ToString(CultureInfo.InvariantCulture);

            lnkAdminProduct.Text = eStoreResources.ProductAdministrationLink;
            lnkAdminProduct.NavigateUrl = SiteRoot + "/eStore/AdminProduct.aspx?pageid="
                                       + pageId.ToString(CultureInfo.InvariantCulture)
                                       + "&mid=" + moduleId.ToString(CultureInfo.InvariantCulture);

            lnkCurrentPage.Text = eStoreResources.ProductEditHeading;
            lnkCurrentPage.NavigateUrl = Request.Url.ToString();

            progressBar.AddTrigger(btnSave);
            Title = SiteUtils.FormatPageTitle(siteSettings, eStoreResources.ProductEditHeading);
            ltrTitle.Text = eStoreResources.ProductEditHeading;
            btnSave.Text = eStoreResources.ProductUpdateButton;
            btnDelete.Text = eStoreResources.ProductDeleteButton;
            btnDelete.Attributes.Add("OnClick", "return confirm('"
                    + eStoreResources.ProductDeleteWarning + "');");

            btnDeleteImg.ImageUrl = ImageSiteRoot + "/Data/SiteImages/delete.gif";
            
            edDescription.WebEditor.ToolBar = ToolBar.FullWithTemplates;
            edDescription.WebEditor.Height = Unit.Parse("350px");

            litSettingsTab.Text = eStoreResources.ProductEditGeneralSettingsLabel;
            litDescriptionTab.Text = eStoreResources.ProductDescriptionTab;
            litMetaTab.Text = eStoreResources.MetaDataTab;

            if (!Page.IsPostBack)
            {
                const decimal defaultPrice = 0;
                txtPrice.Text = defaultPrice.ToString();
            }

            ltrPriceCurrency.Text = eStoreResources.PriceSymbol;
            

            reqName.ErrorMessage = eStoreResources.ProductNameRequired;
            reqPrice.ErrorMessage = eStoreResources.ProductPriceRequired;

            btnAddMeta.Text = eStoreResources.AddMetaButton;
            grdContentMeta.Columns[0].HeaderText = string.Empty;
            grdContentMeta.Columns[1].HeaderText = eStoreResources.ContentMetaNameLabel;
            grdContentMeta.Columns[2].HeaderText = eStoreResources.ContentMetaMetaContentLabel;

            btnAddMetaLink.Text = eStoreResources.AddMetaLinkButton;

            grdMetaLinks.Columns[0].HeaderText = string.Empty;
            grdMetaLinks.Columns[1].HeaderText = eStoreResources.ContentMetaRelLabel;
            grdMetaLinks.Columns[2].HeaderText = eStoreResources.ContentMetaMetaHrefLabel;

            lblImageUrlError.Text = eStoreResources.ImageUrlErrorLabel + ConfigurationManager.AppSettings["AllowedImageFileExtensions"]
                + @" -- " + eStoreResources.ImageUrlErrorLabelFileSize + ConfigurationManager.AppSettings["AllowedImageSize"] + @" KB";

            ltrInfo.Text = eStoreResources.NoCategoryWarning;
            hplAddCategory.Text = eStoreResources.ContinueButton;
            hplAddCategory.NavigateUrl = SiteRoot + "/eStore/AdminCategoryEdit.aspx?pageid=" + pageId.ToInvariantString() + "&mid=" + moduleId.ToInvariantString();

            pnlTax.Visible = config.UseTaxSystem;
        }

        private string GetReturnUrl()
        {
            return SiteRoot + "/eStore/AdminProduct.aspx?pageid="
                + pageId.ToInvariantString()
                + "&mid=" + moduleId.ToInvariantString();
        }

        private void LoadSettings()
        {
            if (CurrentPage.ContainsModule(moduleId))
            {
                //store = StoreHelper.GetStore(siteSettings.SiteGuid, moduleId);
                store = StoreHelper.GetStore();
                Hashtable moduleSettings = ModuleSettings.GetModuleSettings(moduleId);
                config = new eStoreConfiguration(moduleSettings);

            }

            try
            {
                // this keeps the action from changing during ajax postback in folder based sites
                SiteUtils.SetFormAction(Page, Request.RawUrl);
            }
            catch (MissingMethodException)
            {
                //this method was introduced in .NET 3.5 SP1
            }

            siteUser = SiteUtils.GetCurrentSiteUser();

            WebUtils.GetApplicationRoot();
            timeOffset = SiteUtils.GetUserTimeOffset();
            timeZone = SiteUtils.GetUserTimeZone();

            if (store == null) { return; }
            product = new Product(productGuid);
            //currencyCulture = ResourceHelper.GetCurrencyCulture(store.DefaultCurrency);
        }

        private void LoadParams()
        {
            pageId = WebUtils.ParseInt32FromQueryString("pageid", pageId);
            moduleId = WebUtils.ParseInt32FromQueryString("mid", moduleId);
            productGuid = WebUtils.ParseGuidFromQueryString("Product", productGuid);
        }

        protected String GetBeginDate(Object o)
        {
            if ((o == null) || (o.ToString() == String.Empty))
            {
                return timeZone != null ? DateTime.UtcNow.ToLocalTime(timeZone).ToString("g") : DateTime.UtcNow.AddHours(timeOffset).ToString("g");
            }
            if (o is DateTime)
            {
                return timeZone != null ? ((DateTime)o).ToLocalTime(timeZone).ToString("g") : ((DateTime)o).AddHours(timeOffset).ToString("g");
            }

            return o.ToString();

        }

        protected virtual void SetupCss()
        {
            // older skins have this
            if (Page.Master == null) return;
            StyleSheet stylesheet = (StyleSheet)Page.Master.FindControl("StyleSheet");
            if (stylesheet == null) return;
            if (stylesheet.FindControl("styleestore") != null) return;
            Literal cssLink = new Literal
                                  {
                                      ID = "styleestore",
                                      Text = @"<link href='"
                                             + SiteUtils.GetSkinBaseUrl()
                                             +
                                             @"styleestore.css' type='text/css' rel='stylesheet' media='screen' />"
                                  };

            stylesheet.Controls.Add(cssLink);
        }
        
        private bool SaveImageUrl(out string fileName)
        {
            String pathToApplicationsFolder
                = HttpContext.Current.Server.MapPath(
                "~/" + ConfigurationManager.AppSettings["eStoreImagesFolder"]);
            if (!Directory.Exists(pathToApplicationsFolder))
            {
                Directory.CreateDirectory(pathToApplicationsFolder);
            }
            bool flag = false;
            int width = 0;
            int height = 0;
            fileName = string.Empty;
            try
            {
                //Check valid file upload
                if (nuImageUrl.HasFile && nuImageUrl.ContentLength > 0)
                {

                    string fileExtension = Path.GetExtension(nuImageUrl.FileName);
                    Double fileSize = nuImageUrl.ContentLength / 1024;

                    //Kiem tra ten mo rong file upload
                    if (!Utilities.IsValidFileExtension(fileExtension, "AllowedImageFileExtensions"))
                    {
                        lblImageUrlError.Text = eStoreResources.ImageUrlErrorFileExtension;
                        return false;
                    }
                    //Kiem tra kich thuoc file upload
                    if (!Utilities.IsValidFileSize(fileSize, "AllowedImageSize"))
                    {
                        lblImageUrlError.Text = eStoreResources.ImageUrlErrorFileSize + ConfigurationManager.AppSettings["AllowedImageSize"] + @" KB";
                        return false;
                    }
                    string path = Server.MapPath("~/" + ConfigurationManager.AppSettings["eStoreImagesFolder"]);
                    string guid = Guid.NewGuid().ToString().Replace("-", "").ToUpper();
                    System.Drawing.Image image = System.Drawing.Image.FromStream(nuImageUrl.FileContent);
                    nuImageUrl.FileContent.Close();
                    int resizeWidth;
                    int.TryParse(ConfigurationManager.AppSettings["eStoreImageMaxWidth"], out resizeWidth);
                    int resizeHeight;
                    int.TryParse(ConfigurationManager.AppSettings["eStoreImageMaxHeight"], out resizeHeight);
                    int thumbnailWidth;
                    int.TryParse(ConfigurationManager.AppSettings["eStoreImageMaxThumbnailWidth"], out thumbnailWidth);
                    int thumbnailHeight;
                    int.TryParse(ConfigurationManager.AppSettings["eStoreImageMaxThumbnailHeight"], out thumbnailHeight);
                    Utilities.ResizeImage(ref width, ref height, resizeWidth, resizeHeight, image.Width, image.Height);
                    fileName = path + guid + "_t" + fileExtension;
                    if (height != 0)
                    {
                        using (Bitmap bitmap = new Bitmap(image, width, height))
                        {
                            bitmap.Save(fileName, image.RawFormat);
                        }
                    }
                    else
                    {
                        using (Bitmap bitmap = new Bitmap(image, image.Width, image.Width))
                        {
                            bitmap.Save(fileName, image.RawFormat);
                        }
                        //nuImageUrl.MoveTo(fileName, MoveToOptions.Overwrite);
                        //fuImageUrl.PostedFile.SaveAs(fileName);
                    }
                    Utilities.ResizeImage(ref width, ref height, thumbnailWidth, thumbnailHeight, image.Width, image.Height);
                    fileName = path + guid + fileExtension;
                    if (height != 0)
                    {
                        using (Bitmap bitmap = new Bitmap(image, width, height))
                        {
                            bitmap.Save(fileName, image.RawFormat);
                        }
                    }
                    else
                    {
                        using (Bitmap bitmap = new Bitmap(image, image.Width, image.Width))
                        {
                            bitmap.Save(fileName, image.RawFormat);
                        }
                        //nuImageUrl.MoveTo(fileName, MoveToOptions.Overwrite);
                        //fuImageUrl.PostedFile.SaveAs(fileName);
                    }
                    fileName = guid + fileExtension;
                    if (!product.ImageUrl.Equals(string.Empty))
                    {
                        DeleteImageFromServer();
                    }
                    flag = true;
                }
                else
                {
                    flag = true;
                }
            }
            catch (Exception e)
            {
                lblImageUrlError.Visible = true;
                lblImageUrlError.Text = e.Message;//"Error when upload image";
            }
            return flag;
        }

        private void DeleteImageFromServer()
        {
            string thumbnailImageURL = Request.PhysicalApplicationPath + ConfigurationManager.AppSettings["eStoreImagesFolder"] + product.ImageUrl;
            thumbnailImageURL = thumbnailImageURL.Replace("/", "\\");
            string imageURL = thumbnailImageURL.Substring(0, thumbnailImageURL.LastIndexOf(".")) + "_t" + thumbnailImageURL.Substring(thumbnailImageURL.LastIndexOf("."));
            if (File.Exists(imageURL))
            {
                File.Delete(imageURL);
            }
            if (File.Exists(thumbnailImageURL))
            {
                File.Delete(thumbnailImageURL);
            }
        }

        void btnDeleteImg_Click(object sender, ImageClickEventArgs e)
        {
            if (product == null) { product = new Product(productGuid); }

            DeleteImageFromServer();
            divImage.Visible = false;
            product.ImageUrl = "";
            product.Save();
        }

        #region OnInit



        protected override void OnPreInit(EventArgs e)
        {
            AllowSkinOverride = true;
            base.OnPreInit(e);
            SiteUtils.SetupEditor(edDescription);
        }



        protected override void OnInit(EventArgs e)
        {
            LoadSideContent(false, false, true, true, 0);
            base.OnInit(e);

            Load += Page_Load;
            btnSave.Click += btnSave_Click;
            btnDelete.Click += btnDelete_Click;
            
            SuppressPageMenu();
            SuppressGoogleAds();

            grdContentMeta.RowCommand += grdContentMeta_RowCommand;
            grdContentMeta.RowEditing += grdContentMeta_RowEditing;
            grdContentMeta.RowUpdating += grdContentMeta_RowUpdating;
            grdContentMeta.RowCancelingEdit += grdContentMeta_RowCancelingEdit;
            grdContentMeta.RowDeleting += grdContentMeta_RowDeleting;
            grdContentMeta.RowDataBound += grdContentMeta_RowDataBound;
            btnAddMeta.Click += btnAddMeta_Click;

            grdMetaLinks.RowCommand += grdMetaLinks_RowCommand;
            grdMetaLinks.RowEditing += grdMetaLinks_RowEditing;
            grdMetaLinks.RowUpdating += grdMetaLinks_RowUpdating;
            grdMetaLinks.RowCancelingEdit += grdMetaLinks_RowCancelingEdit;
            grdMetaLinks.RowDeleting += grdMetaLinks_RowDeleting;
            grdMetaLinks.RowDataBound += grdMetaLinks_RowDataBound;
            btnAddMetaLink.Click += btnAddMetaLink_Click;
            btnDeleteImg.Click += btnDeleteImg_Click;
        }


        #endregion
    }
}
